import 'package:flutter/material.dart';
import 'package:pdfx/pdfx.dart';
import 'package:untitled1/utils/pdf_loader.dart';
import 'dart:typed_data';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'PDF查看器',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('PDF查看器'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('显示PDF'),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const PdfViewPage(
                  pdfUrl: 'https://zjj.sz.gov.cn/attachment/1/1595/1595106/12236492.pdf',
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

class PdfViewPage extends StatefulWidget {
  final String pdfUrl;

  const PdfViewPage({
    Key? key,
    required this.pdfUrl,
  }) : super(key: key);

  @override
  _PdfViewPageState createState() => _PdfViewPageState();
}

class _PdfViewPageState extends State<PdfViewPage> {
  late PdfControllerPinch _pdfController;
  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _loadPdfFromNetwork();
  }

  Future<void> _loadPdfFromNetwork() async {
    try {
      // 加载PDF数据并转换为Uint8List
      final pdfData = await PdfLoader.loadPdfFromUrl(widget.pdfUrl);
      final pdfBytes = Uint8List.fromList(pdfData);

      _pdfController = PdfControllerPinch(
        document: PdfDocument.openData(
          pdfBytes,
          password: '', // 如果PDF有密码，这里需要提供
        ),
      );

      // 监听PDF加载状态
      _pdfController.document.then((_) {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }).catchError((error) {
        if (mounted) {
          setState(() {
            _isLoading = false;
            _errorMessage = 'PDF加载失败: $error';
          });
        }
      });
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _errorMessage = '发生错误: $e';
        });
      }
    }
  }

  @override
  void dispose() {
    _pdfController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('PDF文档'),
      ),
      body: _isLoading
          ? const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('加载中...'),
          ],
        ),
      )
          : _errorMessage != null
          ? Center(child: Text(_errorMessage!))
          : PdfViewPinch(
        controller: _pdfController,
        onDocumentError: (error) {
          setState(() {
            _errorMessage = 'PDF渲染失败: ${error.toString()}';
          });
        },
      ),
    );
  }
}